package com.ethannhu.todaynews.util

import android.view.LayoutInflater
import java.lang.reflect.ParameterizedType

/**
 * 反射工具类
 */
object ReflectUtil {
    /**
     * 创建 view binding
     */
    fun <T> newViewBinding(layoutInflater: LayoutInflater, clazz: Class<*>): T {
        return try {
            //获取泛型参数对象
            val type: ParameterizedType = try {  //获取父类的泛型类型
                clazz.genericSuperclass as ParameterizedType
            } catch (e: ClassCastException) {
                clazz.superclass.genericSuperclass as ParameterizedType
            }

            val clazzT = type.actualTypeArguments[0] as Class<T>

            //获取 inflate 方法
            val inflateMethod = clazzT.getMethod("inflate", LayoutInflater::class.java)
            inflateMethod.invoke(null, layoutInflater) as T //返回 inflate 之后的 viewbinding
        } catch (e: Exception) {
            e.printStackTrace()
            throw RuntimeException(e)
        }

    }
}